#include "QxDatabasePool.hpp"

#include "QxWorkspaceIO.hpp"
#include "QxWellDatabaseIO.hpp"

bool g_initialized = false;

class QxDatabasePool::QxDatabasePoolPrivate
{
public:

  QxDatabasePoolPrivate( QxDatabasePool* me ) : m_self( me ) {
  }

  QxDatabasePool*         m_self;

  QSqlDatabase            m_database;
};

QxDatabasePool& QxDatabasePool::instance()
{
  static QxDatabasePool selfObject;
  return selfObject;
}

QxDatabasePool::~QxDatabasePool()
{
}

const QSqlDatabase& QxDatabasePool::database() const
{
  Q_ASSERT( g_initialized );

  return _pd->m_database;
}

void QxDatabasePool::setDatabase( const QSqlDatabase& db )
{
  Q_ASSERT( g_initialized );

  if( _pd->m_database.databaseName() != db.databaseName() ) {
    _pd->m_database.close();
    _pd->m_database = db;
    QxWorkspaceIO::createTable( db );
    QxWellDatabaseIO::createTable( db );
    Q_EMIT databaseChanged( db );
  }
}

bool QxDatabasePool::init()
{
  bool result = true;

  g_initialized = true;
  if( !theDatabasePool.database().isOpen() ) {
    QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE" );
    db.setDatabaseName( ":memory:" );
    if( db.open() ) {
      theDatabasePool.setDatabase( db );
    } else {
      result = g_initialized = false;
    }
  }

  result && (g_initialized = true);

  return result;
}

void QxDatabasePool::finish()
{
  QSqlDatabase db = theDatabasePool.database();
  db.close();
  g_initialized = false;
}

QxDatabasePool::QxDatabasePool() : _pd( new QxDatabasePoolPrivate( this ) )
{
}